package com.ruoyi.hospital.utils.interceptors;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.DocInfo;
import com.ruoyi.hospital.utils.ResponseUtil;
import com.ruoyi.hospital.utils.doc.DocTokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/*
* 创建一个医生的接口拦截器
* */
@Component
public class DocInterceptor implements HandlerInterceptor {

    @Autowired
    private DocTokenService docTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用（Controller方法调用之前）
        docTokenService.delLoginUser(request.getHeader("token"));
        // 如果返回false，则停止流程，api不会被调用
        // 如果返回true，则继续执行后续的API
        DocInfo loginUser = docTokenService.getLoginUser(request);
        if(loginUser== null){
            ResponseUtil.write(response, (String) JSON.toJSONString(AjaxResult.error(401,"请登录")));
            return  false;
        }
        return true;
    }
}
